package com.lagou.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务端
 */
public class ServerSocketDemo {

    public static void main(String[] args) throws Exception {
        // 创建线程池
        ExecutorService threadPool = Executors.newCachedThreadPool();
        // 创建ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(9999);
        while(true){
            Thread.sleep(1000);
            // 监听客户端
            final Socket socket = serverSocket.accept();
            System.out.println("有客户端链接");
            // 开启新的线程处理
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    handle(socket);
                }
            });
        }
    }

    private static void handle(Socket socket)  {
        System.out.println("线程ID:" + Thread.currentThread().getId());
        System.out.println("线程name:" + Thread.currentThread().getName());
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // 取出输入流并接收信息
            inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int read = inputStream.read(bytes);
            System.out.println("客户端:" + new String(bytes, 0, read));
            // 取出输出流并返回信息
            outputStream = socket.getOutputStream();
            outputStream.write("没钱".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
